package com.edu.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.edu.admin.entity.SysSchoolRole;
import com.edu.admin.enums.ExceptionEnum;
import com.edu.admin.enums.UseTypeEnum;
import com.edu.admin.service.SchoolRoleMenuService;
import com.edu.admin.service.SchoolRoleService;
import com.edu.admin.common.RestResult;
import com.edu.admin.vo.SchoolRoleMenuVo;
import com.edu.admin.vo.SchoolRoleVo;
import com.github.pagehelper.PageInfo;

/**
 * 校级角色管理
 *  
 * @author Wangjiong
 * 
 */
@RestController
@RequestMapping(value = "/schoolrole", name = "校级角色管理")
public class SchoolRoleController {
	@Autowired
	private SchoolRoleService	schoolRoleService;
	@Autowired
	private SchoolRoleMenuService	schoolRoleMenuService;

	/**
	 *
	 * @apiGroup schoolrole
	 * @api {get} /schoolrole/list 获取学校角色列表
	 * @apiVersion 1.0.0
	 * @apiName getSchoolRoleList
	 *
	 * @apiParam {Long} schoolId 学校id
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": [
		        {
		            "schoolRoleId": 2,
		            "schoolRoleName": "校长",
		            "schoolId": 1,
		            "useType": 0,
		            "menuIds": [
		                4
		            ]
		        },
		        {
		            "schoolRoleId": 6,
		            "schoolRoleName": "教师",
		            "schoolId": 1,
		            "useType": 0,
		            "menuIds": [
		                4
		            ]
		        }
		    ]
		}
	 *
	 *
	 */
    @RequestMapping(value = "list", name = "学校角色列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/schoolrole/list')")
    public RestResult getSchoolRoleList(Long schoolId) throws Exception {

        List<SchoolRoleVo> roleList = schoolRoleService.getSchoolRoleListBySchoolId(schoolId);
        return RestResult.ok(roleList);
    }
    
    /**
	 *
	 * @apiGroup schoolrole
	 * @api {get} /schoolrole/listAllPage 获取学校角色列表（分页）
	 * @apiVersion 1.0.0
	 * @apiName getAllSchoolRoleListPage
	 * @apiParam {Integer} pageNum 页码
	 * @apiParam {Integer} pageSize 每页行数
	 *
	 * @apiParam {Long} schoolId 学校id
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "total": 2,
		        "list": [
		            {
		                "schoolRoleId": 2,
		                "schoolRoleName": "校长",
		                "schoolId": 1,
		                "useType": 0,
		                "menuIds": [
		                    4
		                ]
		            },
		            {
		                "schoolRoleId": 6,
		                "schoolRoleName": "教师",
		                "schoolId": 1,
		                "useType": 0,
		                "menuIds": [
		                    4
		                ]
		            }
		        ],
		        "pageNum": 1,
		        "pageSize": 10,
		        "size": 2,
		        "startRow": 1,
		        "endRow": 2,
		        "pages": 1,
		        "prePage": 0,
		        "nextPage": 0,
		        "isFirstPage": true,
		        "isLastPage": true,
		        "hasPreviousPage": false,
		        "hasNextPage": false,
		        "navigatePages": 8,
		        "navigatepageNums": [
		            1
		        ],
		        "navigateFirstPage": 1,
		        "navigateLastPage": 1,
		        "firstPage": 1,
		        "lastPage": 1
		    }
		}
	 *
	 *
	 */
    @RequestMapping(value = "listAllPage", name = "所有学校角色列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/schoolrole/listAllPage')")
    public RestResult getAllSchoolRoleListPage(@RequestParam(name = "schoolId", required = false) Long schoolId,
    		@RequestParam(name = "pageNum", required = false) Integer pageNum,
			@RequestParam(name = "pageSize", required = false) Integer pageSize)
    		throws Exception {
    	
    	PageInfo<SchoolRoleVo> pageInfo = schoolRoleService.getAllSchoolRoleListPageBySchoolId(pageNum, pageSize, schoolId);
        
        return RestResult.ok(pageInfo);
    }
    
    /**
	 *
	 * @apiGroup schoolrole
	 * @api {post} /schoolrole/save 保存学校角色信息
	 * @apiVersion 1.0.0
	 * @apiName save
	 *
	 * @apiParam {SysSchoolRole} role 学校角色信息
	 * @apiParamExample 请求示例（json）
	 * {
		
			"schoolRoleId": 2,
	        "schoolRoleName": "校长",
	        "schoolId": 1,
	        "useType": 0
		
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "schoolRoleId": 2
		    }
		}
	 *
	 */
	@RequestMapping(value = "save", name = "保存学校角色信息", method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('/schoolrole/save')")
	public RestResult save(@Valid @RequestBody SysSchoolRole role) throws Exception{
		Map<String, Object> result = new HashMap<>();
		
		result = schoolRoleService.saveSchoolRole(role);
	
		return RestResult.ok(result);
	}
	
	/**
	 *
	 * @apiGroup schoolrole
	 * @api {post} /schoolrole/delete 删除班级角色
	 * @apiVersion 1.0.0
	 * @apiName deleteSchoolRole
	 *
	 * @apiParam {Long} schoolRoleId 班级角色id
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
	@RequestMapping(value="/delete" , method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('/schoolrole/delete')")
	public RestResult deleteSchoolRole(@RequestBody Map<String,Object> dataMap) throws Exception {
	   
	   	Long schoolRoleId = MapUtils.getLong(dataMap, "schoolRoleId");
	   	
	   	if (schoolRoleId == null || schoolRoleId<=0)
	   	{
	   		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
	   	}
	  	    			
		int isOk = schoolRoleService.deleteSchoolRole(schoolRoleId);
		if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
	}
	
	/**
	 *
	 * @apiGroup schoolrole
	 * @api {post} /schoolrole/on 启用角色
	 * @apiVersion 1.0.0
	 * @apiName onSchoolRole
	 *
	 * @apiParam {Long} schoolRoleId 学校角色id
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
	@RequestMapping(value="/on" , method = RequestMethod.POST)
  @PreAuthorize("hasAuthority('/schoolrole/on')")
  public RestResult onRole(@RequestBody Map<String,Object> dataMap) throws Exception {
	   
	   	Long schoolRoleId = MapUtils.getLong(dataMap, "schoolRoleId");
	   	
	   	if (schoolRoleId == null || schoolRoleId<=0)
	   	{
	   		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
	   	}
	  	    			
	  	int isOk = schoolRoleService.useSchoolRole(schoolRoleId,UseTypeEnum.ISUSE.getCode());
	  	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
  }
  
  /**
	 *
	 * @apiGroup schoolrole
	 * @api {post} /schoolrole/off 停用角色
	 * @apiVersion 1.0.0
	 * @apiName offSchoolRole
	 *
	 * @apiParam {Long} schoolRoleId 学校角色id
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
	@RequestMapping(value="/off" , method = RequestMethod.POST)
  @PreAuthorize("hasAuthority('/schoolrole/off')")
  public RestResult offSchoolRole(@RequestBody Map<String,Object> dataMap) throws Exception {
 	   
    	Long schoolRoleId = MapUtils.getLong(dataMap, "schoolRoleId");
    	
    	if (schoolRoleId == null || schoolRoleId<=0)
    	{
    		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
    	}
  	    			
	  	int isOk = schoolRoleService.useSchoolRole(schoolRoleId,UseTypeEnum.NOTUSE.getCode());
	  	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
  }
	

  /**
	 *
	 * @apiGroup schoolrole
	 * @api {get} /schoolrole/info 获取学校角色信息
	 * @apiVersion 1.0.0
	 * @apiName getSchoolRole
	 *
	 * @apiParam {Long} schoolRoleId 学校角色id
	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "schoolRoleId": 2,
		        "schoolRoleName": "校长",
		        "schoolId": 1,
		        "useType": 0
		    }
		}
	 *
	 *
	 */
	@RequestMapping(value = "info", name = "学校角色信息", method = RequestMethod.GET)
	@PreAuthorize("hasAuthority('/schoolrole/info')")
	public RestResult getSchoolRole(@RequestParam Long schoolRoleId) throws Exception{
		SysSchoolRole role = null;
		SchoolRoleVo roleVo = null;
		
		role = schoolRoleService.selectByPrimaryKey(schoolRoleId);
		
		if (role!=null)
		{
			roleVo = new SchoolRoleVo();
			BeanUtils.copyProperties(role,roleVo);
		}

		return RestResult.ok(roleVo);
	}
	
	/**
	 *
	 * @apiGroup schoolrole
	 * @api {post} /schoolrole/saveRoleMenu 删除角色
	 * @apiVersion 1.0.0
	 * @apiName saveSchoolRoleMenu
	 *
	 * @apiParam Map<String,Object> paramMap
	 * @apiParamExample 请求示例（json）
 	 * {
		  "roleId":"1"，
		  "menuIds":[1,2,3,4]，
		
		} 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": null
		}
	 *
	 *
	 */
  @RequestMapping(value = "saveSchoolRoleMenu", name = "保存学校角色权限", method = RequestMethod.POST)
  @PreAuthorize("hasAuthority('/schoolrole/saveSchoolRoleMenu')")
  public RestResult saveSchoolRoleMenu(@RequestBody Map<String,Object> paramMap) 
			throws Exception {
	   Long schoolRoleId = MapUtils.getLong(paramMap,"schoolRoleId");
      @SuppressWarnings("unchecked")
	List<Integer> menuIds = (List<Integer>)MapUtils.getObject(paramMap,"menuIds");
      Integer[] ids = new Integer[]{};
      if(menuIds != null){
          ids = new Integer[menuIds.size()];
          menuIds.toArray(ids);
      }
      schoolRoleMenuService.saveSchoolRoleMenu(schoolRoleId,ids);
      return RestResult.ok();
  }
	
  /**
	 *
	 * @apiGroup schoolrole
	 * @api {get} /schoolrole/menulist 学校角色菜单列表
	 * @apiVersion 1.0.0
	 * @apiName getSchoolRoleMenuList
	 *
	 * @apiParam Long schoolRoleId
	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200 
		{
		    "code": 200,
		    "msg": "success",
		    "data": [
		        {
		            "schoolRoleId": 2,
		            "menuId": 4,
		            "schoolRoleName": "校长",
		            "menuName": "教师账号管理"
		        }
		    ]
		}
     * 
     */
    @RequestMapping(value = "menulist", name = "学校角色菜单列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/schoolrole/menulist')")
    public RestResult getSchoolRoleMenuList(Long schoolRoleId) throws Exception {

        List<SchoolRoleMenuVo> roleMenuList = schoolRoleMenuService.getSchoolRoleMenuListBySchoolRoleId(schoolRoleId);
        return RestResult.ok(roleMenuList);
    }
    


}
